import fs from "node:fs/promises";
import path from "node:path";
import { RunnerSpec, TaskHandler } from "../types";
import { resolvePath, ensureDir } from "../utils";
import { writeJsonFile } from "../../../tools/data-processor";

function extractRenderTargets(content: string): string[] {
  const matches = content.match(/render[A-Z][A-Za-z0-9]+/g) || [];
  return Array.from(new Set(matches));
}

export const renderVerifyBelongToTask: TaskHandler = async (spec) => {
  const belongToDir = spec.schema?.belongToDir;
  if (!belongToDir) {
    throw new Error("schema.belongToDir is required for render.verifyBelongTo");
  }

  const absoluteDir = resolvePath(belongToDir);
  const files = await fs.readdir(absoluteDir);
  const renderFunctions: Record<string, string[]> = {};

  for (const file of files.filter((file) => file.endsWith(".tsx"))) {
    const filePath = path.join(absoluteDir, file);
    const content = await fs.readFile(filePath, "utf-8");
    renderFunctions[file] = extractRenderTargets(content);
  }

  const reportRelative = spec.report?.path
    ? spec.report.path.replace(/\.json$/, "-render.json")
    : path.join("analysis", `${spec.component}-render-report.json`);
  const outputPath = resolvePath(reportRelative);
  await ensureDir(path.dirname(outputPath));
  await writeJsonFile(outputPath, renderFunctions);

  return {
    summary: `Analyzed ${Object.keys(renderFunctions).length} render files`,
    outputPaths: { renderReport: reportRelative },
    data: renderFunctions,
  };
};
